package org.itboys.store.weixin;

import org.apache.commons.lang3.StringUtils;
import org.itboys.baseobject.service.CityService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.pay.weixin.WeixinPaySignTool;
import org.itboys.store.constant.ProductConstant;
import org.itboys.store.dto.ConfirmOrderDto;
import org.itboys.store.entity.Order;
import org.itboys.store.manager.StoreOrderMemberService;
import org.itboys.store.service.StoreOrderService;
import org.itboys.store.service.StoreProductService;
import org.itboys.weixin.service.WeixinConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by huml on 2016/4/19.
 * 微信订单业务
 */
@RestController
@RequestMapping("/store/weixin/order")
public class StoreOrderWeixinController extends BaseController {

    @Autowired
    private StoreOrderService orderService;
    @Autowired
    private StoreProductService productService;
    @Autowired
    private CityService cityService;
    @Autowired
    private WeixinConfigService weixinConfigService;
    @Autowired
    private StoreOrderMemberService storeOrderMemberService;

    /**
     * 跳转立即购买
     * @param productId
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/buyNow")
    public ModelAndView buyNow(@RequestParam("productId") Long productId,
                               @RequestParam(value = "addressId", required = false) Long addressId,
                               HttpServletRequest request,
                               @RequestParam("num")Integer num,
                       Model model){
        FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
        ConfirmOrderDto dto = storeOrderMemberService.buyNow(productId, member.getId(), num, addressId);
        model.addAttribute("dto", dto);
        model.addAttribute("productId", productId);
        model.addAttribute("addressId", addressId);
        model.addAttribute("num", num);
        return new ModelAndView("site/orderConfirm");
    }

    /**
     * 立即购买生成订单   返回支付相关的参数
     * @param productId
     * @param num
     * @param couponId
     * @param payMethod
     * @param addressId
     * @param memo
     * @param response
     */
    @RequestMapping("/buyNowCreateOrder")
    public void buyNowCreateOrder(HttpServletRequest request,
                                  @RequestParam("productId") Long productId,
                                  @RequestParam("num")int num, @RequestParam("couponId")Long couponId,
                                  @RequestParam("payMethod")Integer payMethod, @RequestParam("addressId")Long addressId,
                                  @RequestParam("memo")String memo, HttpServletResponse response){
        try {
            String spbillCreateIp = request.getRemoteAddr();
            if(StringUtils.isBlank(spbillCreateIp) || spbillCreateIp.equals("0:0:0:0:0:0:0:1")){
                spbillCreateIp = "127.0.0.1";
            }
            FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
            Object object = storeOrderMemberService.buyNowCreateOrder(productId, member.getId(), num, couponId,spbillCreateIp, payMethod, addressId, memo);
            if(object instanceof Integer){
                AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgCodeResultDO((Integer)object, "下单失败"));
            } else {
                AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgResultDO((String)object, CommonConstants.SUCCESS));
            }
        } catch (Exception e) {
            logger.error("/weixin/order/buyNowCreateOrder error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 购物车转订单的确认订单页
     * @param request
     * @param carIds
     * @param model
     * @return
     */
    @RequestMapping("/carConfirm")
    public ModelAndView carConfirm(HttpServletRequest request,
                                   @RequestParam("carIds")List<Long> carIds,
                                   @RequestParam(value = "addressId", required = false) Long addressId,
                                   Model model){
        FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
        ConfirmOrderDto dto = storeOrderMemberService.carConfirm(member.getId(), carIds, addressId);
        model.addAttribute("dto", dto);
        model.addAttribute("carIds", carIds.toString().replace("[", "").replace("]", ""));
        model.addAttribute("addressId", addressId);
        return new ModelAndView("site/orderConfirm");
    }

    /**
     * 购物车转订单
     * @param carIds
     * @param addressId
     * @param payMethod
     * @param memo
     * @param request
     * @param response
     */
    @RequestMapping("/carToOrder")
    public void carToOrder(@RequestParam("carIds")List<Long> carIds,
                           @RequestParam("addressId")Long addressId, @RequestParam("payMethod")Integer payMethod,
                           @RequestParam("memo")String memo,
                           HttpServletRequest request, HttpServletResponse response){
        try {
            String spbillCreateIp = request.getRemoteAddr();
            if(StringUtils.isBlank(spbillCreateIp) || spbillCreateIp.equals("0:0:0:0:0:0:0:1")){
                spbillCreateIp = "127.0.0.1";
            }
            FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
            Object object = storeOrderMemberService.carToOrder(member.getId(), carIds, addressId, payMethod, memo, spbillCreateIp);
            if(object instanceof Integer){
                AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgCodeResultDO((Integer)object, "下单失败"));
            } else if (object instanceof String) {
                String result = (String)object;
                if(result.startsWith("http")){
                    AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgResultDO((String)object, CommonConstants.SUCCESS));
                } else {
                    AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgCodeResultDO(-3, (String)object));
                }
            }
        } catch (Exception e) {
            logger.error("/store/weixin/order/carToOrder error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 单笔订单发起支付
     * @param request
     * @param orderId
     * @param response
     */
    @RequestMapping("/singleOrderPay")
    public void singleOrderPay(HttpServletRequest request,
                               @RequestParam("orderId")Long orderId,
                               HttpServletResponse response){
        try {
            String spbillCreateIp = request.getRemoteAddr();
            if(StringUtils.isBlank(spbillCreateIp) || spbillCreateIp.equals("0:0:0:0:0:0:0:1")){
                spbillCreateIp = "127.0.0.1";
            }
            Object object = storeOrderMemberService.singleOrderPay(orderId, spbillCreateIp);
            if(object instanceof Integer){
                AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO((Integer)object, "下单失败"));
            } else {
                AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgResultDO((WeixinPaySignTool)object, CommonConstants.SUCCESS));
            }
        } catch (Exception e) {
            logger.error("/store/weixin/order/singleOrderPay error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 微信支付异步回调
     * @param request
     * @param response
     */
    @RequestMapping("/weixinNotify/{orderNo}")
    public void weixinNotify(HttpServletRequest request,
                             @PathVariable("orderNo")String orderNo,
                             HttpServletResponse response){
        try {
            String result = storeOrderMemberService.weixinNofity(request, orderNo);
            AjaxUtils.renderText(response, result);
        } catch (Exception e) {
            logger.error("/store/weixin/order/weixinNotify error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 单笔订单微信支付异步回调
     * @param request
     * @param response
     */
    @RequestMapping("/weixinNotifySingle/{orderNo}")
    public void weixinNotifySingle(HttpServletRequest request,
                                   @PathVariable("orderNo")String orderNo,
                                   HttpServletResponse response){
        try {
            String result = storeOrderMemberService.weixinNotifySingle(request, orderNo);
            AjaxUtils.renderText(response, result);
        } catch (Exception e) {
            logger.error("/store/weixin/order/weixinNotifySingle error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 支付成功
     * @return
     */
    @RequestMapping("/success")
    public ModelAndView success(){
        return new ModelAndView("site/paySuccess1");
    }

    /**
     * 跳转我的订单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/myOrderVM")
    public ModelAndView myOrderVM(HttpServletRequest request,
                                  @RequestParam(value = "status", required = false)Integer status,
                                  Model model){
        FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
        List<Order> list = storeOrderMemberService.myOrder(member.getId(), status, request);
        model.addAttribute("orders", list);
        model.addAttribute("status", status);
        model.addAttribute("type", "2");
        return new ModelAndView("site/myOrder1");
    }

    /**
     * 分页获取我的订单
     * @param request
     * @param status
     * @param response
     */
    @RequestMapping("/myOrder")
    public void myOrder(HttpServletRequest request,
                        @RequestParam("status")Integer status,
                        HttpServletResponse response){
        try {
            FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
            List<Order> list = storeOrderMemberService.myOrder(member.getId(), status, request);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgResultDO(list, CommonConstants.SUCCESS));
        } catch (Exception e) {
            logger.error("/store/weixin/order/myOrder error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 取消订单
     * @param orderId
     * @param response
     */
    @RequestMapping("/cancelOrder")
    public void cancelOrder(@RequestParam("orderId")Long orderId,
                            HttpServletResponse response){
        try {
            Order order = orderService.getById(orderId);
            if(order.getStatus().equals(ProductConstant.OrderStatic.ORDER_STATUS_CREATE)){
                order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_CANCLE);
                orderService.update(order);
            }
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgCodeResultDO(0, CommonConstants.SUCCESS));
        } catch (Exception e) {
            logger.error("/store/weixin/order/cancelOrder error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

    /**
     * 确认收货
     * @param orderId
     * @param response
     */
    @RequestMapping("/confirmGet")
    public void confirmGet(@RequestParam("orderId")Long orderId,
                           HttpServletResponse response){
        try {
            storeOrderMemberService.confirmGet(orderId);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getMsgCodeResultDO(0, CommonConstants.SUCCESS));
        } catch (Exception e) {
            logger.error("/store/weixin/order/confirmGet error", e);
            AjaxUtils.renderJsonporJson(response, null, ResultPageDOHelper.getErrorResultDO(-1, CommonConstants.FAIL));
        }
    }

}
